package lzzy.net.chaper04_jpa;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CommentService {
    @Autowired
    CommentRepository commentRepository;


    public List<Comment> selectAll(){
        return commentRepository.findAll();
    }

    public void selectById(Integer id){
        Optional<Comment> comment= commentRepository.findById((id));
        if (comment.isPresent())
            System.out.println(comment);
        else
            System.out.println("没找到");
    }
    public void delById(Integer id){
        commentRepository.deleteById(id);
    }
    public  Comment  addComment(String content, String author,Integer aId){
        Comment comment =new Comment();
        comment.setAuthor(author);
        comment.setContent(content);
        comment.setArticleId(aId);
        return commentRepository.save(comment);
    }

    public  Comment  updaComment(Integer id,String content, String author,Integer aId) {
        Comment comment = new Comment();
        comment.setId(id);
        comment.setAuthor(author);
        comment.setContent(content);
        comment.setArticleId(aId);
        return commentRepository.save(comment);
    }

    public List<Comment> selectAllSortByAId(){
        return commentRepository.findAll(Sort.by(Sort.Direction.ASC,"aId"));
    }

    public  List<Comment> selectAllPage(int page,int size){
        Pageable pageable = PageRequest.of(page,size);
        return commentRepository.findAll(pageable).getContent();
    }

    public  List<Comment> selectByExample(String author){
        Comment comment =new Comment();
        comment.setAuthor(author);
        Example<Comment> commentExample = Example.of(comment);
        return commentRepository.findAll(commentExample);
    }
}
